package com.health.userbackstage.web.control;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.health.userbackstage.mapper.MemberMapper;
import com.health.userbackstage.pojo.Member;
import com.health.userbackstage.pojo.Order;
import com.health.userbackstage.pojo.Report;
import com.health.userbackstage.pojo.result.Result;
import com.health.userbackstage.pojo.result.ResultEnum;
import com.health.userbackstage.service.MemberService;
import com.health.userbackstage.service.OrderService;
import com.health.userbackstage.service.OrderSettingService;
import com.health.userbackstage.utils.RegularExpression;
import com.health.userbackstage.utils.SnowflakeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderSettingService orderSettingService;

    @GetMapping
    public Result findByPage(Integer currentPage, Integer pageSize, Integer total) {
        IPage<Member> ipage = new Page<>(currentPage,pageSize);

        IPage<Member> page = memberService.page(ipage);

        return Result.success(ipage);
    }

    @GetMapping("{queryString}")
    public Result findOne(@PathVariable("queryString") String queryString) {
        Member member = new Member();
        member.setFileNumber(queryString);
        Member one = memberService.findOneByFileNumber(member);
        List<Member> list = new ArrayList<>();
        if (one == null){
            member.setFileNumber(null);
            member.setName(queryString);
            Member two = memberService.findOneByName(member);
            if (two != null){
                list.add(two);
            }
        }else {
            list.add(one);
        }
        return Result.success(list);
    }

    @PostMapping
    @Transactional
    public Result insertMember(@RequestBody Member member){
        member.setRegtime(new Date());

        Result error = MemberController.error(member);
        if (error.getCode()==400){
            return error;
        }
        String password = member.getPassword();
        String encode = encoder.encode(password);
        member.setPassword(encode);

        boolean saveOrUpdate = memberService.saveOrUpdate(member);
        if (saveOrUpdate){
            return Result.success();
        }
        return Result.fail(ResultEnum.FAILED_ADD);
    }

    @GetMapping("/insertReset")
    public Result insertMemberReset(){
        Member member = new Member();
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        long snowId = snowflakeUtils.nextId();
        member.setId(snowId);
        member.setFileNumber(String.valueOf(snowId));
        return Result.success(member);
    }

    @GetMapping("/memberUpdateInit")
    public Result updateMemberReset(Long id){
        Member member = memberService.getById(id);

        if (member == null){
            return Result.fail(ResultEnum.FAILED_FIND);
        }
        return Result.success(member);
    }

    @PutMapping
    @Transactional
    public Result updateMember(@RequestBody Member member){

        Result error = MemberController.error(member);
        if (error.getCode()==400){
            return error;
        }

        String encode = encoder.encode(member.getPassword());
        member.setPassword(encode);

        boolean saveOrUpdate = memberService.saveOrUpdate(member);
        if (!saveOrUpdate){
            return Result.fail(ResultEnum.FAILED_EDIT);
        }

        return Result.success(member);
    }

    @DeleteMapping("/{id}")
    @Transactional
    public Result deleteMember(@PathVariable("id") Long id){

        int result = 0;

        //查询memberId对应的Order预约人
        List<Order> orders = memberService.findByMemberId(id);
        //查询memberId对应的report预约报告
        List<Report> reports = memberService.findReportByMemberId(id);

        //如果member有预约人order
        if (orders != null){
            for (Order order : orders) {
                //修改ordersetting表中的可预约数减1
                boolean updateResult = orderSettingService.updateReservationsByOrderDate(order.getOrderDate());
                if (updateResult == false){
                    result = 1;
                }

                //删除order预约人
                boolean deleteById = orderService.deleteById(order.getId());
                //删除对应的`order_report`预约报告关系表中的数据
                boolean deleteOrderReportByOrderId = orderSettingService.deleteOrderReportByOrderId(order.getId());
                if (deleteById == false ||deleteOrderReportByOrderId == false){
                    result = 1;
                }
            }
        }

        //如果报告不为空
        if (reports != null){
            for (Report report : reports) {
                //删除对应的各个report
                boolean deleteReportById = memberService.deleteReportById(report.getId());
                if (deleteReportById == false){
                    result = 1;
                }
            }
        }

        //根据id删除会员
        boolean removeResult = memberService.removeById(id);
        if (removeResult == false){
            result = 1;
        }

        if (result == 0){
            return Result.success();
        }else {
            return Result.fail(ResultEnum.FAILED_DEL);
        }
    }

    public static Result error(Member member){

        //判断身份证号码
        if (member.getIdcard() == null || RegularExpression.determineIdCard(member.getIdcard())){
            return Result.fail("请输入正确的身份证号码");
        }

        //判断身份证号码
        if (member.getSex() == null || member.getSex() == ""){
            return Result.fail("请选择正确的性别");
        }

        //判断身份证号码
        if (member.getName() == null || member.getName() == ""){
            return Result.fail("请输入正确的名称");
        }

        //判断手机号
        if (member.getPhoneNumber() == null || !RegularExpression.determine(member.getPhoneNumber())){
            return Result.fail("请输入正确的手机号");
        }

        //判断邮箱
        if (member.getEmail() == null || !RegularExpression.determineEmail(member.getEmail())){
            return Result.fail("请输入正确的邮箱");
        }

        //判断生日
        if ((member.getBirthday() == null || member.getBirthday().after(new Date()))){
            return Result.fail("请输入正确的生日");
        }

        //判断密码
        if ((member.getPassword() == null || member.getPassword().length() < 6)){
            return Result.fail("请输入正确的密码");
        }

        return Result.success();
    }
}
